package com.hawthorn.admin.service.sysmenu.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.hawthorn.admin.model.po.SysMenuPO;
import com.hawthorn.admin.repository.SysMenuMapper;
import com.hawthorn.admin.repository.SysUserFavoriteMapper;
import com.hawthorn.admin.repository.SysUserRecentMapper;
import com.hawthorn.admin.service.sysmenu.SysMenuService;
import com.hawthorn.component.utils.bean.Map2ObjUtil;
import com.hawthorn.entity.dto.SysUserFavoriteDTO;
import com.hawthorn.entity.dto.SysUserRecentDTO;
import com.hawthorn.entity.po.SysUserFavoritePO;
import com.hawthorn.entity.po.SysUserRecentPO;
import com.hawthorn.platform.exception.BizCode;
import com.hawthorn.platform.redis.RedisMyClient;
import com.hawthorn.platform.service.ExcelApiService;
import com.hawthorn.platform.service.TransResultService;
import com.hawthorn.platform.utils.common.ArrayMyUtil;
import com.hawthorn.platform.utils.common.MyUtil;
import com.hawthorn.platform.utils.iassert.AssertMyUtil;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>todo 系统菜单服务实现类 </p>
 * @author: andyten@tom.com | xukaixing@hotmail.com
 * @created: 2021/11/25 5:28 PM
 * @version v1.0.2
 * @copyright: Copyright (c)  andyten
 */
@Service
public class SysMenuServiceImpl implements SysMenuService
{
  @Resource
  private RedisMyClient redisMyClient;
  @Resource
  private SysUserRecentMapper sysUserRecentMapper;
  @Resource
  private SysUserFavoriteMapper sysUserFavoriteMapper;
  @Resource
  private TransResultService transResultService;
  @Resource
  private SysMenuMapper sysMenuMapper;
  @Resource
  private ExcelApiService excelApiService;

  /**
   * <p>todo 获取最近访问菜单</p>
   * @param: userId
   * @return: java.util.List<com.hawthorn.entity.dto.SysUserRecentDTO>
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/1 9:34 AM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/1    andy.ten        v1.0.1             init
   */
  @Override
  public List<SysUserRecentDTO> findUserRecentMenus(Long userId)
  {
    List<SysUserRecentDTO> recentMenus;
    recentMenus = sysUserRecentMapper.findUserRecentMenus(userId);

    return recentMenus;
  }

  /**
   * <p>todo 根据用户id删除最近访问同名的菜单</p>
   * @param: userId
   * @param: menuId
   * @return: boolean
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/1 9:34 AM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/1    andy.ten        v1.0.1             init
   */
  @Override
  public boolean delRecentMenu(Long userId, Long menuId)
  {
    LambdaQueryWrapper<SysUserRecentPO> lambdaQuery = Wrappers.lambdaQuery();
    lambdaQuery.eq(SysUserRecentPO::getUserId, userId);
    lambdaQuery.eq(SysUserRecentPO::getMenuId, menuId);
    return sysUserRecentMapper.remove(lambdaQuery);
  }

  /**
   * <p>todo 保存最近访问菜单</p>
   * @param: userId
   * @param: userAccount
   * @param: menuId
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/1 9:34 AM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/1    andy.ten        v1.0.1             init
   */
  @Override
  public void saveRecentMenu(Long userId, String userAccount, Long menuId)
  {
    SysUserRecentDTO sysUserRecentDTO = new SysUserRecentDTO();
    sysUserRecentDTO.setUserId(userId);
    sysUserRecentDTO.setMenuId(menuId);
    Map<String, Object> menuMap = redisMyClient.getMenuInfo(String.valueOf(menuId));
    sysUserRecentDTO.setAccount(userAccount);
    sysUserRecentDTO.setMenuCode((String) menuMap.get("code"));
    sysUserRecentDTO.setMenuIcon((String) menuMap.get("icon"));
    sysUserRecentDTO.setMenuTitle((String) menuMap.get("title"));
    sysUserRecentDTO.setMenuTitleen((String) menuMap.get("titleen"));
    sysUserRecentDTO.setMenuUrl((String) menuMap.get("url"));

    sysUserRecentMapper.save(sysUserRecentDTO.transDto2Po(SysUserRecentPO.class));
  }

  /**
   * <p>todo 获取收藏夹菜单</p>
   * @param: userId
   * @return: java.util.List<com.hawthorn.entity.dto.SysUserFavoriteDTO>
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/1 9:34 AM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/1    andy.ten        v1.0.1             init
   */
  @Override
  public List<SysUserFavoriteDTO> findUserFavoriteMenus(Long userId)
  {
    List<SysUserFavoriteDTO> recentMenus;
    recentMenus = sysUserFavoriteMapper.findUserFavoriteMenus(userId);

    return recentMenus;
  }

  /**
   * <p>todo todo 保存收藏夹菜单</p>
   * @param: userId
   * @param: userAccount
   * @param: menuId
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/1 9:34 AM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/1    andy.ten        v1.0.1             init
   */
  @Override
  public void saveFavoriteMenu(Long userId, String userAccount, Long menuId)
  {
    SysUserFavoriteDTO sysUserFavoriteDTO = new SysUserFavoriteDTO();
    sysUserFavoriteDTO.setUserId(userId);
    sysUserFavoriteDTO.setMenuId(menuId);
    Map<String, Object> menuMap = redisMyClient.getMenuInfo(String.valueOf(menuId));
    sysUserFavoriteDTO.setAccount(userAccount);
    sysUserFavoriteDTO.setMenuCode((String) menuMap.get("code"));
    sysUserFavoriteDTO.setMenuIcon((String) menuMap.get("icon"));
    sysUserFavoriteDTO.setMenuTitle((String) menuMap.get("title"));
    sysUserFavoriteDTO.setMenuTitleen((String) menuMap.get("titleen"));
    sysUserFavoriteDTO.setMenuUrl((String) menuMap.get("url"));
    sysUserFavoriteMapper.save(sysUserFavoriteDTO.transDto2Po(SysUserFavoritePO.class));
  }

  /***
   * <p>todo 列表查询</p >
   * @param conditions 查询条件
   * @param page  * @return : com.baomidou.mybatisplus.core.metadata.IPage<java.util.Map<java.lang.String,java.lang.Object>>
   * @author: wcz
   * @date: 2022/7/7 11:36
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   *
   * 2022/7/21 wcz v1.0.1 新增数据字典菜单层级,缓存,隐藏
   */


  @Override
  public IPage<Map<String, Object>> findMenu(String conditions, Page<Map<String, Object>> page)
  {
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("bizType", "dic|ywlx");
    transHash.put("status", "dic|yxzt");
    transHash.put("external", "dic|sf");
    transHash.put("type", "dic|cdcj");
    transHash.put("hidden", "dic|sf01");
    transHash.put("cache", "dic|sf01");
    OrderItem oi = new OrderItem();
    oi.setColumn("code");
    oi.setAsc(true);
    List<OrderItem> al = page.getOrders();
    al.add(oi);
    page.setOrders(al);
    IPage<Map<String, Object>> menu = sysMenuMapper.findMenu(page, conditions);
    return transResultService.transResult(menu, transHash);
  }

  /***
   * <p>todo 新增菜单</p >
   * @param params  * @return : java.util.Map<java.lang.String,java.lang.Object>
   * @author: wcz
   * @date: 2022/7/21 11:04
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/7/21 wcz v1.0.1 新增数据字典菜单层级,缓存,隐藏
   */
  @Override
  public Map<String, Object> saveMenu(Map<String, Object> params)
  {
    SysMenuPO SysMenuPO = Map2ObjUtil.toObject(params, SysMenuPO.class);
    AssertMyUtil.notNull(SysMenuPO, BizCode.VARIABLE_NOT_NULL, "SysMenuPO");
    //重名验证
    Integer companyIsExist = sysMenuMapper.checkMenu(SysMenuPO);
    if (companyIsExist != 0)
    {
      AssertMyUtil.errMsg("菜单名称重复");
    }
    sysMenuMapper.save(SysMenuPO);
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("external", "dic|sf");
    transHash.put("status", "dic|yxzt");
    transHash.put("bizType", "dic|ywlx");
    transHash.put("type", "dic|cdcj");
    transHash.put("hidden", "dic|sfyc");
    transHash.put("cache", "dic|sfhc");
    return transResultService.transResult(SysMenuPO.toMaps(), transHash);
  }

  /**
   * <p>todo 修改菜单</p >
   * @param id 菜单Id
   * @param params  * @return : java.util.Map<java.lang.String,java.lang.Object>
   * @author: wcz
   * @date: 2022/7/8 13:13
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/7/8 wcz v1.0.1 新增数据字典菜单层级,缓存,隐藏
   */

  @Override
  public Map<String, Object> updateMenu(Long id, Map<String, Object> params)
  {
    SysMenuPO sysMenuPO = Map2ObjUtil.toObject(params, SysMenuPO.class);
    AssertMyUtil.notNull(sysMenuPO, BizCode.VARIABLE_NOT_NULL, "SysMenuPO");
    QueryWrapper<SysMenuPO> queryWrapper = new QueryWrapper<>();
    queryWrapper.eq("title", sysMenuPO.getTitle());
    SysMenuPO result = sysMenuMapper.selectOne(queryWrapper);
    if (null != result && !result.getId().equals(sysMenuPO.getId()))
    {
      AssertMyUtil.errMsg("菜单名称重复!");
    }
    sysMenuMapper.updateById(sysMenuPO);
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("external", "dic|sf");
    transHash.put("status", "dic|yxzt");
    transHash.put("biz_type", "dic|ywlx");
    transHash.put("type", "dic|cdcj");
    transHash.put("hidden", "dic|sfyc");
    transHash.put("cache", "dic|sfhc");
    return transResultService.transResult(sysMenuPO.toMaps(), transHash);

  }

  /***
   * <p>todo 删除菜单</p >
   * @param id  * @return : java.lang.Integer
   * @author: wcz
   * @date: 2022/7/8 13:13
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/7/8 wcz v1.0.1 新增数据字典菜单层级,缓存,隐藏
   */
  @Override
  public Integer removeMenu(Long id)
  {
    QueryWrapper<SysMenuPO> queryWrapper = new QueryWrapper<>();
    queryWrapper.lambda().eq(SysMenuPO::getId, id);
    SysMenuPO sysMenuPO = sysMenuMapper.selectOne(queryWrapper);
    Integer status = sysMenuPO.getStatus();
    if (status == 100201)
    {
      AssertMyUtil.errMsg("菜单启用状态不可以删除!");
    }
    return sysMenuMapper.deleteById(id);
  }

  /***
   * <p>todo 导出</p >
   * @param response 获取数据
   * @param fileName 导出文件名
   * @param param  * @return : void
   * @author: wcz
   * @date: 2022/7/11 11:19
   * @version: 1.0.1
   * Modification History:
   * Date Author Version Description
   * -----------------------------------------------------------
   * 2022/7/11 wcz v1.0.1 init
   */
  @Override
  public void exportMenuData(HttpServletResponse response, String fileName, Map<String, Object> param) throws IOException
  {
    String header = MyUtil.getValue(param.get("header"));
    String params = MyUtil.getValue(param.get("param"));
    String qc = MyUtil.getConditionsWhere(params, null);
    List<List<String>> headList = new ArrayList<>();
    List<String> headFields = excelApiService.toHeader(header, headList);
    String fields = ArrayMyUtil.join(headFields.toArray(), ",");
    List<Map<String, Object>> dataList = sysMenuMapper.exportMenu(fields, qc);
    HashMap<String, String> transHash = new HashMap<>();
    transHash.put("status", "dic|yxzt");
    transHash.put("kind", "dic|qdslb");
    transHash.put("external", "dic|sf");
    transHash.put("cache", "dic|sfhc");
    excelApiService.export(response, fileName, headFields, headList, dataList, transHash);
  }

  @Override
  public Integer changeStatus(long id, String params)
  {
    AssertMyUtil.notNull(id, BizCode.METHOD_ARGS_NOTNULL, "id");
    //查询下级组织有效状态
    if (sysMenuMapper.findById(id) != 0 && Integer.parseInt(params) == 100202)
    {
      AssertMyUtil.errMsg("修改失败,该菜单下存在启用菜单!");
    }
    UpdateWrapper<SysMenuPO> updateWrapper = new UpdateWrapper<>();
    SysMenuPO sysMenuPO = sysMenuMapper.selectById(id);
    sysMenuPO.setStatus(Integer.parseInt(params));
    updateWrapper.eq("id", id);
    return sysMenuMapper.update(sysMenuPO, updateWrapper);
  }

  /**
   * <p>todo 根据用户id删除收藏夹同名的菜单</p>
   * @param: userId
   * @param: menuId
   * @return: boolean
   * @author: andyten@tom.com | xukaixing@hotmail.com
   * @date: 2021/12/1 9:34 AM
   * @version: 1.0.1
   * Modification History:
   * Date         Author          Version            Description
   * -----------------------------------------------------------
   * 2021/12/1    andy.ten        v1.0.1             init
   */
  @Override
  public boolean delFavoriteMenu(Long userId, Long menuId)
  {
    LambdaQueryWrapper<SysUserFavoritePO> lambdaQuery = Wrappers.lambdaQuery();
    lambdaQuery.eq(SysUserFavoritePO::getUserId, userId);
    lambdaQuery.eq(SysUserFavoritePO::getMenuId, menuId);
    return sysUserFavoriteMapper.remove(lambdaQuery);
  }

}
